import React, { useEffect, useState } from 'react'
import { DeleteOutlined, UnorderedListOutlined, ExclamationCircleOutlined, FileSyncOutlined } from '@ant-design/icons';
import { Table, Button, Modal, notification } from 'antd'
import axios from 'axios'
const { confirm } = Modal
export default function NewDraft(props) {
    const [dataSource, setdataSource] = useState([])
    const { username } = JSON.parse(localStorage.getItem('token'))
    useEffect(() => {
        query()
    }, [username])

    const query = () => {
        axios.get(`/news?author=${username}&auditState=0&_expand=category`).then(res => {
            setdataSource(res.data)
        })
    }
    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            render: (id) => <b>{id}</b>
        },
        {
            title: '新闻标题',
            dataIndex: 'title',
            render: (title, item) => {
                return <a href={`#/news-manage/preview/${item.id}`}>{title}</a>
            }
        },
        {
            title: '作者',
            dataIndex: 'author'
        },
        {
            title: '分类',
            dataIndex: 'category',
            render: (category) => <b>{category.title}</b>
        },

        {
            title: '操作',
            render: (item) => {
                return <div>
                    <Button onClick={() => {
                        props.history.push(`/news-manage/update/${item.id}`)
                    }} style={{ margin: '4px' }} type="primary" shape="circle" icon={<UnorderedListOutlined />} />

                    <Button onClick={() => confirmMethod(item)} style={{ margin: '4px' }} type="danger" shape="circle" icon={<DeleteOutlined />} />
                    <Button onClick={() => audit(item)} style={{ margin: '4px' }} type="dashed" shape="circle" icon={<FileSyncOutlined />} />
                </div >
            }
        },
    ]

    const confirmMethod = (item) => {
        confirm({
            title: '您确定要删除掉吗',
            icon: <ExclamationCircleOutlined />,
            content: '一旦删除将不可恢复',
            onOk() {
                deleteReady(item)
            },
            onCancel() {

            },
        });
    }
    const deleteReady = (item) => {
        axios.delete(`/news/${item.id}`).then(() => {
            query()
        })
    }

    const audit = (item) => {
        axios.patch(`/news/${item.id}`, {
            auditState: 1
        }).then(res => {
            props.history.push('/audit-manage/list')
            notification.info({
                message: '通知',
                description: `您可以通过审核列表中查看你的新闻`,
                placement: 'bottomRight'
            })
        })
    }
    return (
        <div>
            <Table dataSource={dataSource} columns={columns} pagination={{
                pageSize: 10
            }} rowKey={(item) => item.id} />
        </div>
    )
}

